from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, Session
from models.user import Base
from models.post import Post, Tag  # 引入新模型
from models.auth import UserAuth  # 引入实名认证模型
import os

# 数据库连接配置
DATABASE_URL = os.getenv(
    "DATABASE_URL",
    "mysql+pymysql://root:12345@localhost:3306/redbook1?charset=utf8mb4"
)

# 创建数据库引擎
engine = create_engine(DATABASE_URL, echo=True, pool_pre_ping=True)

# 创建Session工厂
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)


def init_db():
    """初始化数据库，创建所有表"""
    Base.metadata.create_all(bind=engine)


def get_db():
    """
    获取数据库会话的依赖注入函数
    """
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

